package com.tarena.lab;

import java.sql.*;
import java.io.*;

public class SQLTools {
	public static void main(String[] args) {
		// 连接任意数据库
		Connection con = getConn();
		// 处理用户命令
		process(con);
		// 结束
		JdbcUtil.close(null, null, con);
		System.out.println("bye-bye");
	}

	/**
	 *得到练﹃︻︼﹂
	 * @return
	 */
	private static Connection getConn() {
		// String driverName = "oracle.jdbc.driver.OracleDriver";
		// String url = prompt("请输入URL:");
		// String userName = prompt("请输入用户名:");
		// String pwd = prompt("请输入密码:");
		Connection con = null;
		try {
			// Class.forName(driverName);
			con = JdbcUtil.getConn();
			// con = DriverManager.getConnection(url,userName,pwd);
			con.setAutoCommit(false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	private static void process(Connection con) {
		boolean flag = true;
		while (flag) {
			String command = getCommand();
			if ("quit".equals(command)) {
				flag = false;
			} else if ("commit".equals(command) || "rollback".equals(command)) {
				processTransaction(con, command);
			}
			{
				processSQL(con, command);
			}
		}
	}

	private static String prompt(String message) {
		System.out.print(message);
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String input = null;
		try {
			input = in.readLine();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return input;
	}

	private static String getCommand() {
		String message = "SQL>";
		boolean flag = true;
		StringBuffer sb = new StringBuffer();
		String command = "";
		int i = 0;
		while (flag) {
			if (++i > 1)
				message = i + ">";
			sb.append(" " + prompt(message));
			command = sb.toString().trim();
			if (command.endsWith(";")) {
				flag = false;
			}
		}
		return command.substring(0, command.length() - 1).trim();
	}

	public static void processSQL(Connection con, String sql) {
		PreparedStatement ps = null;
		ResultSet rs = null;
		boolean f = true;
		try {
			ps = con.prepareStatement(sql);
			f = ps.execute();
			if (f) {
				rs = ps.getResultSet();
				JdbcUtil.printRs(rs);
			} else {
				int i = ps.getUpdateCount();
				System.out.println("更新成功-" + i);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (f) {
				System.out.println("查询失败");
			} else {
				System.out.println("更新失败");
			}
		} finally {
			JdbcUtil.close(rs, ps, null);
		}
	}

	private static void processTransaction(Connection con, String command) {
		try {
			if ("commit".equals(command)) {
				con.commit();
			} else {
				con.rollback();
			}
			System.out.println(command + "成功");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(command + "失败");
		}
	}
}
